package framework.core.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@SuppressWarnings("unchecked")
public class SecurityInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		HttpSession session = req.getSession(true);

		String requestUri = req.getRequestURI();
		String contextPath = req.getContextPath();
		String url = requestUri.substring(contextPath.length());
		
		if (url.indexOf("login") != -1 || url.indexOf("init") != -1) {
			return true;
		} else {
			System.out.print("auth"+session.getAttribute("auth") +"     ");
			
			Set<String> set = (Set<String>) session.getAttribute("auth");
			 
			List<String> list = new ArrayList<String>(set);
			if (list != null && list.size() > 0 && list.contains(url)) {
				return true;
			} else {
				if (isAjaxRequest(req)) {
					try {
						response.getWriter().print("login1");
					} catch (IOException e) {
						e.printStackTrace();
					}
				} else {
					res.sendRedirect(req.getContextPath() + "/login.jsp");
				}
			}
			return false;
		}
	}

	private boolean isAjaxRequest(HttpServletRequest request) {
		String header = request.getHeader("X-Requested-With");
		if (header != null && "XMLHttpRequest".equals(header))
			return true;
		else
			return false;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}
}
